package com.youxin.busfoundation.common;


import org.apache.log4j.Logger;

import com.youxin.foundation.interfaces.ExecuteStatement;
import com.youxin.foundation.utils.thread.BaseThreadPool;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;
import com.youxin.foundation.utils.thread.SingleThreadPool;

import sun.misc.Signal;
import sun.misc.SignalHandler;
/**
 * 接收关机信号
 * @author yingde.cao
 *
 */
public class HandleShutdownApp {
	private static HandleShutdownApp handleShutdownApp=new HandleShutdownApp();
	private ExecuteStatement executeStatement;
	public static HandleShutdownApp instance()
	{
		return handleShutdownApp;
	}
	private static Logger logger = Logger.getLogger(HandleShutdownApp.class);

	@SuppressWarnings("restriction")
	public void handleSignal(ExecuteStatement executeStatement) {
		try {
			this.executeStatement=executeStatement;
			// Signal.handle(new Signal(signalName), this);			
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					logger.warn("正在关闭程序 ...");
				}
			});
			Signal.handle(new Signal("INT"), signalHandler);
			Signal.handle(new Signal("TERM"), signalHandler);
			

		} catch (IllegalArgumentException e) {
			// 可能这个信号,并不支持这个平台或JVM作为目前配置
			logger.error(e.toString(), e);
		}
	}

	@SuppressWarnings("restriction")
	private SignalHandler signalHandler = new SignalHandler() {
		@Override
		public void handle(Signal sig) {
			long waitTimes=2;
			long t=0;
			BaseThreadPool.stop();			
			ScheduleThreadPool.stop();			
			SingleThreadPool.stop();			
			try {
				if(executeStatement!=null)
				{
					executeStatement.execute();
				}
			} catch (Exception e) {
			}
			while (t<waitTimes) {
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					// TODO: handle exception
				}
				++t;
				
			}
			logger.warn("收到关闭程序的请求");
			System.exit(0);
		}
	};

}
